import { v1 as uuidv1 } from 'uuid'

export const clientId = uuidv1()
// 下面是相关占位符解释如下：

// # 下面是配置相关服务的地址,配置的相关占位符解释如下：

// # 样例1
// # 假设当前网页地址是https://www.example.com:8899/a/b/c
// # {hostname} => 'www.example.com'              # 当前网址的域名或者是ip
// # {port} => '8899'                             # 当前网址的端口号，如果当前网址没有写明端口号，则https默认端口号443，http默认端口号是80
// # {scheme} => 'https'                          # 当前网址的协议， 'https'或者是'http'
// # {ws-scheme} => 'wss'                         # 当前网址对应的websocket的协议, 'wss'或者'ws'
// # {pathname[0]} => 'a'                         # pathname 为网址对应的路径的数组 ['a', 'b', 'c']
// # {pathname[1]} => 'b'                         # pathname 为网址对应的路径的数组 ['a', 'b', 'c']
// # {pathname[2]} => 'c'                         # pathname 为网址对应的路径的数组 ['a', 'b', 'c']
// # {client-id}                                  # 每次网页都用生成一个uuid作为当前的回话的id

// # 样例2
// # 假设当前网页地址是http://www.example.com/a/b/c/
// # {hostname} => 'www.example.com'              # 当前网址的域名或者是ip
// # {port} => '80'                               # 当前网址的端口号，如果当前网址没有写明端口号，则https默认端口号443，http默认端口号是80
// # {scheme} => 'http'                           # 当前网址的协议， 'https'或者是'http'
// # {ws-scheme} => 'ws'                          # 当前网址对应的websocket的协议, 'wss'或者'ws'
// # {pathname[0]} => 'a'                         # pathname 为网址对应的路径的数组 ['a', 'b', 'c', '']
// # {pathname[1]} => 'b'                         # pathname 为网址对应的路径的数组 ['a', 'b', 'c', '']
// # {pathname[2]} => 'c'                         # pathname 为网址对应的路径的数组 ['a', 'b', 'c', '']
// # {pathname[3]} => ''                          # pathname 为网址对应的路径的数组 ['a', 'b', 'c', '']
// # {client-id}                                  # 每次网页都用生成一个uuid作为当前的回话的id

function processPath(path: string): string {
  const { hostname, port, protocol } = window.location
  const scheme = protocol.replace(':', '')
  const pathname = window.location.pathname.substring(1).split('/')
  let ret = path
  ret = ret.replace('{hostname}', hostname)
  ret = ret.replace('{scheme}', scheme)
  ret = ret.replace('{ws-scheme}', scheme === 'https' ? 'wss' : 'ws')
  ret = ret.replace('{port}', port || (scheme === 'https' ? '443' : '80'))
  ret = ret.replace('{client-id}', clientId)
  for (let i = 0; i < pathname.length; i++) {
    ret = ret.replace(`{pathname[${i}]}`, pathname[i])
  }
  return ret
}

function makeBasePath(): string {
  const orig = location.origin
  let ps = location.pathname.split('/')
  let p = ps.slice(0, ps.length - 1).join('/')
  return `${orig}${p}`
}

const BASE_API_PATH = processPath(import.meta.env.VITE_BASE_API_PATH)
const WS_PATH = processPath(import.meta.env.VITE_WS_PATH)

type Config = {
  basePath: string
  baseApiPath: string
  wsPath: string
  baseMapPath: string
  seaweedfsPath: string
  clientId: string
}

export let config: Config

async function requestConfig(): Promise<Config> {
  console.log('start to request config')
  const url = `${BASE_API_PATH}/config`
  const resp = await fetch(url)
  if (resp.status < 200 || resp.status >= 300) {
    throw Error('failed to get ' + url)
  }
  const cfg = await resp.json()
  return {
    basePath: makeBasePath(),
    baseApiPath: BASE_API_PATH,
    wsPath: WS_PATH,
    baseMapPath: cfg.mapPath,
    seaweedfsPath: cfg.seaweedfs,
    clientId
  }
}

export async function setup() {
  config = await requestConfig()
  console.log('get config', config)
}
